var client_auth = '';
var date = new Date(); // 日期初始化
var BaseUrl = ''; // ajax请求基础路径
var that = new Vue();

function formatDate(date, fmt) {
	if (/(y+)/.test(fmt)) {
		fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
	}
	var o = {
		'M+': date.getMonth() + 1,
		'd+': date.getDate(),
		'h+': date.getHours(),
		'H+': date.getHours(),
		'm+': date.getMinutes(),
		's+': date.getSeconds()
	};
	for (var k in o) {
		if (new RegExp('(' + k + ')').test(fmt)) {
			var str = o[k] + '';
			fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? str : padLeftZero(str));
		}
	}
	return fmt;
}

/**
*  确认弹框
	header：头部信息默认为“提示”，
	msg：提示信息默认为空，
	confirmButtonText：确认按钮文本，cancelButtonText：取消按钮文本，
	type：弹出框类型默认info，
	center：bool值 弹出框是否居中默认为false
	succFun 确认回调
	errFun  取消回调
*/
function confirmMsg(header, msg, succFun, errFun, confirmButtonText, cancelButtonText, type, center, useHtml) {
	that.$confirm(msg ? msg : '', header ? header : '提示', {
		confirmButtonText: confirmButtonText ? confirmButtonText : '',
		cancelButtonText: cancelButtonText ? cancelButtonText : '',
		type: type ? type : 'warning',
		center: center ? center : false,
		dangerouslyUseHTMLString: useHtml == true ? true : false,
		callback: function (action, instance) {
			if (action == 'confirm') {
				succFun();
			} else {
				errFun();
			}
		},
	})
}
/**
*    操作消息提示
 header：头部信息默认为“提示”，
 msg：提示信息默认为空，
 confirmButtonText：确认按钮文本，
 type：弹出框类型默认info，
 center：bool值 弹出框是否居中默认为false
 callback 回调
*/
function alertMsg(header, msg, confirmButtonText, type, center, callback, useHtml) {
	that.$alert(msg ? msg : '', header ? header : '提示', {
		confirmButtonText: confirmButtonText ? confirmButtonText : '确定',
		type: type ? type : 'info',
		center: center ? center : false,
		dangerouslyUseHTMLString: useHtml == true ? true : false,
		callback: function (action) {
			if (!callback) {
				return;
			} else if (action == 'confirm') {
				callback();
			}

		}
	});
}


/**
* 请求服务器;
* module  模块名称必填
* @param  param 参数
* @cb 回调函数
*/
function request(module, param, cbSun, cbErr) {
	requestProxy({ url: param.url, type: param.type, data: param.data, async: param.async, ContentType: param.ContentType, timeout: param.timeout }, cbSun, cbErr);
}

/**
* 请求参数:
* @param  param { url type data timeout} callback
*/
function requestProxy(param, cbSun, cbErr) {
	if (param.type == 'get') {
		if (param.data) {
			param.data.time = new Date().getTime();
		} else {
			param.data = {
				time: new Date().getTime()
			};
		}
	}
	$.ajax({
		type: param.type || 'post',
		dataType: "json",
		data: param.data,
		url: BaseUrl + param.url,
		headers: {
			'Content-Type': param.ContentType || 'application/x-www-form-urlencoded;',
			'Authorization': 'bearer ' + localStorage.getItem("access_token")
		},
		xhrFields: {
			withCredentials: true
		},
		async: typeof param.async === "undefined" ? true : param.async,
		crossDomain: true,
		timeout: param.timeout || 30000,
		success: function (res) {
			if (typeof cbSun === "function") cbSun(res)
		},
		error: function (err, textStatus) {
			typeof cbErr === "function" && cbErr(err);
			if (err.status == '401' && err.responseJSON.clientModel == 'rsServer') {
				client_auth = err.responseJSON.clientAuth;
				var url = window.location.href;
				var serverUrl = err.responseJSON.ssoServerUrl;
				var b = new Base64();
				var baseUrl = b.encode(url);
				window.location.href = '/framework-ui/src/main/resources/static/agcloud/login/login.html?reBackurl=' + baseUrl + '&client_auth=' + client_auth + '&serverUrl=' + serverUrl;
			} else if (textStatus === "timeout") {
				that.$message.error('请求超时，请重试');
			} else if (err.status == '401' && err.responseJSON.clientModel == 'ssoClient') {
				window.top.location.reload();
			} else {
				// 2020-05-27 去掉该错误信息
				// that.$message({
				//   message: err.message?err.message:''+'未获取到登录信息，请刷新页面！',
				//   type: 'error'
				// });
			}
		}
	});
}

function padLeftZero(str) {
	return ('00' + str).substr(str.length);
}
function Base64() {

	// private property
	_keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";

	// public method for encoding
	this.encode = function (input) {
		var output = "";
		var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
		var i = 0;
		input = _utf8_encode(input);
		while (i < input.length) {
			chr1 = input.charCodeAt(i++);
			chr2 = input.charCodeAt(i++);
			chr3 = input.charCodeAt(i++);
			enc1 = chr1 >> 2;
			enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
			enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
			enc4 = chr3 & 63;
			if (isNaN(chr2)) {
				enc3 = enc4 = 64;
			} else if (isNaN(chr3)) {
				enc4 = 64;
			}
			output = output +
				_keyStr.charAt(enc1) + _keyStr.charAt(enc2) +
				_keyStr.charAt(enc3) + _keyStr.charAt(enc4);
		}
		return output;
	}

	// public method for decoding
	this.decode = function (input) {
		var output = "";
		var chr1, chr2, chr3;
		var enc1, enc2, enc3, enc4;
		var i = 0;
		input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
		while (i < input.length) {
			enc1 = _keyStr.indexOf(input.charAt(i++));
			enc2 = _keyStr.indexOf(input.charAt(i++));
			enc3 = _keyStr.indexOf(input.charAt(i++));
			enc4 = _keyStr.indexOf(input.charAt(i++));
			chr1 = (enc1 << 2) | (enc2 >> 4);
			chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
			chr3 = ((enc3 & 3) << 6) | enc4;
			output = output + String.fromCharCode(chr1);
			if (enc3 != 64) {
				output = output + String.fromCharCode(chr2);
			}
			if (enc4 != 64) {
				output = output + String.fromCharCode(chr3);
			}
		}
		output = _utf8_decode(output);
		return output;
	}

	// private method for UTF-8 encoding
	_utf8_encode = function (string) {
		string = string.replace(/\r\n/g, "\n");
		var utftext = "";
		for (var n = 0; n < string.length; n++) {
			var c = string.charCodeAt(n);
			if (c < 128) {
				utftext += String.fromCharCode(c);
			} else if ((c > 127) && (c < 2048)) {
				utftext += String.fromCharCode((c >> 6) | 192);
				utftext += String.fromCharCode((c & 63) | 128);
			} else {
				utftext += String.fromCharCode((c >> 12) | 224);
				utftext += String.fromCharCode(((c >> 6) & 63) | 128);
				utftext += String.fromCharCode((c & 63) | 128);
			}

		}
		return utftext;
	}

	// private method for UTF-8 decoding
	_utf8_decode = function (utftext) {
		var string = "";
		var i = 0;
		var c = c1 = c2 = 0;
		while (i < utftext.length) {
			c = utftext.charCodeAt(i);
			if (c < 128) {
				string += String.fromCharCode(c);
				i++;
			} else if ((c > 191) && (c < 224)) {
				c2 = utftext.charCodeAt(i + 1);
				string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
				i += 2;
			} else {
				c2 = utftext.charCodeAt(i + 1);
				c3 = utftext.charCodeAt(i + 2);
				string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
				i += 3;
			}
		}
		return string;
	}
}

/**
 * 作者： johnny Li  日期：2020/04/29
 * 错误信息弹窗封装
 * 请求参数:
 * @param {
 *  errorTips: 错误提示信息 
 *  errorMsg：更多的错误信息
 *  close: 关闭回调函数
 * } 
 */
var errorComponent = Vue.extend({
	template: '<div ref="error" class="error-dialog">\
    <div class="error-box">\
    <div class="error-head">\
    <img :src="ctx + \'/agcloud/framework/js-lib/agcloud-lib/images/icon-error_dialog.png\'" alt="">\
    <i class="close-icon close-sign el-icon-close" @click="close"></i>\
    </div>\
    <div class="error-title">错误提示</div>\
    <div class="error-tip">\
    {{errorTips}}\
    <span class="icon-more" v-if="errorMsg" @click="isShowMore = !isShowMore">{{isShowMore ? "收起" : "更多"}}</span>\
    </div>\
    <div class="more-errorMsg" v-show="isShowMore">\
    {{errorMsg}}\
    </div>\
    <div class="error-btn-box">\
    <button class="close-sign" @click="close">我知道了</button>\
    </div>\
    </div>\
    </div>',
	data: function () {
		return {
			ctx: ctx,
			isShowDialog: true, // 通过这个属性，控制是否移除dom元素
			errorTips: '',
			errorMsg: '',
			isShowMore: false
		}
	},
	methods: {
		close: function () {
			this.isShowDialog = false;
			this.a_close && this.a_close();
		}
	},
	watch: {
		isShowDialog: function (cur, old) {
			if (cur === false) {
				this.$refs.error.parentNode.removeChild(this.$refs.error);
			}
		}
	}
})

var errorAlert = function (o) {
	var alertDom = new errorComponent({
		el: document.createElement('div') //将Alert组件挂载到新创建的div上 
	})
	document.body.appendChild(alertDom.$el); //把Alert组件的dom添加到body里 

	alertDom.errorTips = o.errorTips;
	alertDom.errorMsg = o.errorMsg;

	// 关闭事件
	alertDom.a_close = o.close || null;
}

Vue.prototype.$errorAlert = errorAlert;

// util start 公共方法
var UTIL = {};
(function () {
	UTIL = {
		// time => 2019-09-09 12:12:12
		formatDate: function (time, formatStr) {
			if (!time) return '';
			formatStr = formatStr || 'yyyy-MM-dd hh:mm';
			if (typeof time == 'string' && time.split('-').length > 1) {
				return time.substring(0, formatStr.length);
			}
			var date = new Date(time);
			if (!date) return '';
			return formatDate(date, formatStr);
		},
		// 获取当前网页url参数
		getUrlParam: function (name) {
			var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
			var r = window.location.search.substr(1).match(reg);
			if (r != null) {
				return unescape(r[2]);
			}
			return null;
		},
		// 关闭当前页面
		closeCurrentWindow: function () {
			window.close();
		},
		// 延迟关闭页面
		delayCloseWindow: function (time) {
			window.setTimeout(function () {
				UTIL.closeCurrentWindow();
			}, time || 2000);
		},
		// 文件类型对应字体文件数据
		staticIconData: {
			"7Z": { text: "&#xe63c", color: "rgb(87, 193, 255)" },
			"AI": { text: "&#xe63d", color: "rgb(255, 132, 0)" },
			"AVI": { text: "&#xe63e", color: "rgb(239, 52, 80)" },
			"BMP": { text: "&#xe63f", color: "rgb(201, 190, 24)" },
			"EPS": { text: "&#xe640", color: "rgb(64, 123, 248)" },
			"EXE": { text: "&#xe641", color: "rgb(246, 228, 0)" },
			"FLV": { text: "&#xe642", color: "rgb(218, 60, 9)" },
			"DOC": { text: "&#xe643", color: "rgb(56, 120, 222)" },
			"DOCX": { text: "&#xe643", color: "rgb(56, 120, 222)" },
			"GIF": { text: "&#xe644", color: "rgb(132, 220, 0)" },
			"MOV": { text: "&#xe645", color: "rgb(176, 215, 0)" },
			"HTML": { text: "&#xe646", color: "rgb(108, 182, 0)" },
			"MP4": { text: "&#xe647", color: "rgb(52, 130, 240)" },
			"PDF": { text: "&#xe648", color: "#fb7878" },
			"MP3": { text: "&#xe649", color: "rgb(71, 77, 226)" },
			"PPT": { text: "&#xe64a", color: "rgb(248, 82, 7)" },
			"PPTX": { text: "&#xe64a", color: "rgb(248, 82, 7)" },
			"PNG": { text: "&#xe64b", color: "rgb(252, 204, 0)" },
			"PSD": { text: "&#xe64c", color: "rgb(54, 118, 244)" },
			"RAR": { text: "&#xe64d", color: "rgb(26, 142, 247)" },
			"SVG": { text: "&#xe64e", color: "rgb(26, 142, 247)" },
			"SWF": { text: "&#xe64f", color: "rgb(181, 107, 0)" },
			"RP": { text: "&#xe650", color: "rgb(113, 60, 190)" },
			"TIF": { text: "&#xe651", color: "rgb(67, 167, 59)" },
			"TXT": { text: "&#xe652", color: "rgb(85, 215, 224)" },
			"ZIP": { text: "&#xe653", color: "rgb(220, 78, 193)" },
			"JPG": { text: "&#xe654", color: "rgb(61, 182, 251)" },
			"WPS": { text: "&#xe655", color: "rgb(51, 211, 157)" },
			"TAR": { text: "&#xe656", color: "rgb(186, 76, 215)" },
			"XSL": { text: "&#xe657", color: "rgb(139, 199, 85)" },
			"XSLX": { text: "&#xe657", color: "rgb(139, 199, 85)" },
			"DWG": { text: "&#xe70f;", color: "#3878DE" },
			"DXF": { text: "&#xe70e;", color: "#FE830C" },
		},
		getIconData: function (type) {
			var defalutData = { text: "&#xe6b1", color: "rgb(56, 120, 222)" };
			return UTIL.staticIconData[type.toUpperCase()] || defalutData;
		},
		getIconText: function (type) {
			return UTIL.getIconData(type).text;
		},
		getIconData: function (type) {
			return UTIL.getIconData(type).color;
		},
	};
})();
// util  end